import java.sql.*;

/**
 * 银行转账机制演示事务机制
 * 重点三行代码：
 * con.setAutoCommit(false);//开启事务
 * con.commit();//手动提交事务
 * con.rollback();//回滚事务
 */
public class JDBC事务机制演示 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement psta = null;
        //ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //获取数据库链接

            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xclmf", "root", "552200");

            //获取预编译操作数据库对象
            con.setAutoCommit(false);//开启事务
            String sql = "update `bank` set money=? where id=?";
            psta = con.prepareStatement(sql);
            psta.setDouble(1, 15000);
            psta.setInt(2, 1);
            int count = psta.executeUpdate();

            psta.setDouble(1, 5000);
            psta.setInt(2, 2);
            count += psta.executeUpdate();

            //执行sql语句
            System.out.println(count == 2 ? "转账成功！" : "转账失败！");
            con.commit();//手动提交事务
            //处理结果集
        } catch (Exception e) {
            if (con != null) {//回滚事务
                try {
                    con.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
            System.out.println("代码出错！");
        } finally {
            //释放资源
//            if (rs != null) {
//                try {
//                    rs.close();
//                } catch (SQLException throwables) {
//                    throwables.printStackTrace();
//                }
//            }
            if (psta != null) {
                try {
                    psta.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}